/**
 * contactdepartment服务实现
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.service.impl;


import com.sxf.crm.entity.Contact;
import com.sxf.crm.entity.ContactDepartment;
import com.sxf.crm.entity.ContactDepartmentId;
import com.sxf.crm.entity.Department;
import com.sxf.crm.repository.ContactDepartmentRepository;
import com.sxf.crm.service.ContactDepartmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 联系人部门服务实现类
 * 
 * <p>提供联系人部门关系的业务操作实现</p>
 * 
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/6/1
 */
@Service
@RequiredArgsConstructor
public class ContactDepartmentServiceImpl implements ContactDepartmentService {

    private final ContactDepartmentRepository contactDepartmentRepository;

    @Override
    public ContactDepartment createContactDepartment(Contact contact, Department department) {
        ContactDepartment contactDepartment = new ContactDepartment(contact, department);
        return contactDepartmentRepository.save(contactDepartment);
    }

    @Override
    public List<ContactDepartment> getByContactId(Long contactId) {
        return contactDepartmentRepository.findByIdContactId(contactId);
    }

    @Override
    public List<ContactDepartment> getByDepartmentId(Long departmentId) {
        return contactDepartmentRepository.findByIdDepartmentId(departmentId);
    }

    @Override
    public void deleteContactDepartment(Long contactId, Long departmentId) {
        contactDepartmentRepository.deleteById(new ContactDepartmentId(contactId, departmentId));
    }

    @Override
    @Transactional
    public List<ContactDepartment> createContactDepartments(Contact contact, List<Department> departments) {
        return departments.stream()
            .map(department -> {
                ContactDepartment contactDepartment = new ContactDepartment(contact, department);
                return contactDepartmentRepository.save(contactDepartment);
            })
            .toList();
    }
}
